/************************************************************************
 * The code is owned by mainframer.cn and Shang Tao
 * Without aproval of mainframer.cn and Shang Tao, removing the copyright
 * infomation is regarded as invassion of proprietary copyright
 ***********************************************************************/
package com.mr.qa.dao.impl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;

import com.mr.qa.bo.Answer;

/**
 * Data access object (DAO) for domain model class Answer.
 * @see .Answer
 * @author MyEclipse - Hibernate Tools
 */
public class AnswerDAO extends BaseHibernateDAO {

    private static final Log log = LogFactory.getLog(AnswerDAO.class);

	//property constants
	public static final String CONTENT = "content";
	public static final String REFERENCE = "reference";
	public static final String FILE = "file";
	public static final String STATE = "state";
	public static final String POLL_COUNT = "pollCount";
	public static final String IS_ANONYMOUS = "isAnonymous";

    
    public void save(Answer transientInstance) {
        log.debug("saving Answer instance");
        try {
            getSession().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
    
    public void update(Answer transientInstance) {
        log.debug("update Answer instance");
        try {
            getSession().update(transientInstance);
            log.debug("update successful");
        } catch (RuntimeException re) {
            log.error("update failed", re);
            throw re;
        }
    }
    
	public void delete(Answer persistentInstance) {
        log.debug("deleting Answer instance");
        try {
            getSession().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }
    
    public Answer findById( java.lang.Integer id) {
        log.debug("getting Answer instance with id: " + id);
        try {
            Answer instance = (Answer) getSession()
                    .get("com.mr.qa.bo.Answer", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
    
    public List findAll() {
        log.debug("finding QuestionCategory instance by example");
        try
        {
            Query queryObject = getSession().
            createQuery("from Answer as model order by model.id desc");
            if(this.getPageNo().intValue() > 0 && this.getRecordCount().intValue() > 0)
            {
            	queryObject.setFirstResult((getPageNo().intValue() - 1)* getRecordCount().intValue());
            	queryObject.setMaxResults(getRecordCount().intValue());
            }
            List results = queryObject.list();
            log.debug("find by example successful, result size: " + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }  
    //viewed by other person
    public List findUserAnswers(Integer userId)
    {
        try
        {
            //2009.2.8 anonymous answers not counted
            String queryString = "from Answer as model where model.mrIaskUser.id= ? " +
            "and model.mrIaskQuestion.mrIaskCategory.onlyForAdmin = ? and " +
            "model.mrIaskQuestion.mrIaskCategory.state != ? " +
            "and model.mrIaskQuestion.state != ? and model.isAnonymous is false " +
            "order by model.id desc";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, userId);
            queryObject.setParameter(1, "N");
            queryObject.setParameter(2, "1");
            queryObject.setParameter(3, "4");
            if(this.getPageNo().intValue() > 0 && this.getRecordCount().intValue() > 0){
                queryObject.setFirstResult((getPageNo().intValue() - 1)* getRecordCount().intValue());
                queryObject.setMaxResults(getRecordCount().intValue());
            }
            List results = queryObject.list();
            return results;
        }catch (RuntimeException re)
        {
            throw re;
        }
    }
    //viewed by self
    public List findMyAnswers(Integer userId) 
    {
        try
        {
            //2009.2.8 anoonymous answers not counted?
            //and model.isAnonymous is false
            String queryString = "from Answer as model " +
            "where model.mrIaskUser.id= ? and model.mrIaskQuestion.state != ?"
            +" order by model.id desc";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, userId);
            queryObject.setParameter(1, "4");
            //System.out.println("AnswerDAO:"+this.getPageNo()+","+this.getRecordCount());
            //log.info(this.getPageNo()+","+this.getRecordCount());
            if(this.getPageNo().intValue() > 0 && this.getRecordCount().intValue() > 0)
            {
                queryObject.setFirstResult((getPageNo().intValue() - 1)* getRecordCount().intValue());
                queryObject.setMaxResults(getRecordCount().intValue());
            }
            List results = queryObject.list();
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }      
    
    public int countUserAnswers(Integer userId) 
    {
        try
        {
            //2009.2.8 anonymous answers not counted
            String queryString = "select count(*) from Answer as model " +
            "where model.mrIaskUser.id= ? and " +
            "model.mrIaskQuestion.mrIaskCategory.onlyForAdmin = ? and " +
            "model.mrIaskQuestion.mrIaskCategory.state != ? and " +
            "model.mrIaskQuestion.state != ? and model.isAnonymous is false ";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, userId);
            queryObject.setParameter(1, "N");
            queryObject.setParameter(2, "1");
            queryObject.setParameter(3, "4");
            long longCount = (Long)queryObject.uniqueResult();
            return (int)longCount;
        } 
        catch(RuntimeException re)
        {
            log.error(re);
            throw re;
        }
    }
    
    
    public int countMyAnswers(Integer userId) 
    {
        try
        {
            //2009.2.8 anonymous answers nout counted?
            //and model.isAnonymous is false
            String queryString = "select count(*) from Answer as model " +
            "where model.mrIaskUser.id = ? and model.mrIaskQuestion.state != ?";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, userId);
            queryObject.setParameter(1, "4");
            long longCount = (Long)queryObject.uniqueResult();
            //System.out.println("countMyAnswers longCount="+longCount);
            return (int)longCount;
        } 
        catch(RuntimeException re)
        {
            log.error(re);
            throw re;
        }
    }
    
    public List findByExample(Answer instance) {
        log.debug("finding Answer instance by example");
        try {
            List results = getSession()
                    .createCriteria("com.mr.qa.bo.Answer")
                    .add(Example.create(instance))
            .list();
            log.debug("find by example successful, result size: " + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }    
    
    public List findByProperty(String propertyName, Object value) {
      log.debug("finding Answer instance with property: " + propertyName
            + ", value: " + value);
      try {
         String queryString = "from Answer as model where model." 
         						+ propertyName + "= ?";
         Query queryObject = getSession().createQuery(queryString);
		 queryObject.setParameter(0, value);
		 if(this.getPageNo().intValue() > 0 && this.getRecordCount().intValue() > 0){
			 queryObject.setFirstResult((getPageNo().intValue() - 1)*getRecordCount().intValue());
			 queryObject.setMaxResults(getPageNo().intValue() * getRecordCount().intValue());
         }
		 return queryObject.list();
      } catch (RuntimeException re) {
         log.error("find by property name failed", re);
         throw re;
      }
	}

	public List findByContent(Object content) {
		return findByProperty(CONTENT, content);
	}
	
	public List findByReference(Object reference) {
		return findByProperty(REFERENCE, reference);
	}
	
	public List findByFile(Object file) {
		return findByProperty(FILE, file);
	}
	
	public List findByState(Object state) {
		return findByProperty(STATE, state);
	}
	
	public List findByPollCount(Object pollCount) {
		return findByProperty(POLL_COUNT, pollCount);
	}
	
	public List findByIsAnonymous(Object isAnonymous) {
		return findByProperty(IS_ANONYMOUS, isAnonymous);
	}
	
    public Answer merge(Answer detachedInstance) {
        log.debug("merging Answer instance");
        try {
            Answer result = (Answer) getSession()
                    .merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(Answer instance) {
        log.debug("attaching dirty Answer instance");
        try {
            getSession().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
    
    public void attachClean(Answer instance) {
        log.debug("attaching clean Answer instance");
        try {
            getSession().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
}